package test.merge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import test.merge.domain.Order;
import test.merge.domain.Stock;
import test.merge.dto.order.OrderDTO;
import test.merge.mapper.OrderMapper;
import test.merge.service.IOrderService;
import test.merge.service.IStockService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：张任豪
 * @date ：2022/7/19 18:29
 * @description：
 */
@AllArgsConstructor
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private IStockService stockService;

    @Override
    public List<Stock> queryMerge(List<Order> orderList) {
        int sum;
        List<Stock> stockList = new ArrayList<>();
        if (null != orderList && orderList.size() > 0){
            for (Order order : orderList) {
                order = getByGoodsId(order.getGoodsId());
                Stock stock = stockService.getByGoodsId(order.getGoodsId());

                if (stock != null){
                    sum = order.getNumber() + stock.getNumber();
                    stock.setNumber(sum);
                    stockList.add(stock);
                }

            }
        }
        return stockList;
    }


    @Override
    public List<Stock> merge() {
        List<Stock> list = new ArrayList<>();
        list().forEach(order -> {
            Stock stock = stockService.getByGoodsId(order.getGoodsId());
            stock.setNumber(order.getNumber() + stock.getNumber());
            list.add(stock);
        });
        return list;
    }

    @Override
    public void save(OrderDTO orderDTO) {
        if (orderDTO != null){
            List<Order> saveOrder = new ArrayList<>();
            orderDTO.getOrder().forEach(or -> {
                Order order = getByGoodsId(or.getGoodsId());
                if (order == null){
                    or.setOrderId(orderDTO.getOrderId());
                    saveOrder.add(or);
                }else {
                    update(new UpdateWrapper<Order>().set("number",or.getNumber() + order.getNumber()).eq("goodsId",order.getGoodsId()));
                }
                boolean b = stockService.decStock(or.getGoodsId(), or.getNumber());
            });
            saveBatch(saveOrder);
        }
    }

    /**
     * 通过goodsId获取Order
     * @param goodsId
     * @return
     */
    private Order getByGoodsId(String goodsId) {
        if (StringUtils.isEmpty(goodsId)){
            return null;
        }
        return getOne(new QueryWrapper<Order>().eq("goodsId",goodsId));
    }
}
